package com.gscitysfy.cus.drain.modules.special.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gscitysfy.cus.drain.modules.special.service.DrainSpecialService;
import com.gscitysfy.cus.drain.modules.special.service.ForRestClient;
import com.gscitysfy.cus.drain.modules.special.vo.DeviceTypeInfo;
import com.gscitysfy.cus.drain.modules.special.vo.DeviceTypeShowVo;
import com.gscitysfy.cus.drain.modules.special.vo.MonitorRequest;
import com.gscitysfy.cus.drain.utils.CoordinateTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class DrainSpecialServiceImpl implements DrainSpecialService {
//    @Resource
//    IDrainStationTypeRlDeviceTypeService deviceTypeService;
//    @Resource
//    IDrainStationChTypeService chTypeService;
    @Resource
    ForRestClient forestClient;

    private static Map<String,String> map = new HashMap<>();

    private static Map<String, DeviceTypeShowVo> showMap = new HashMap<>();

    static {
        map.put("jcsb005","易涝点水位计"); //水位
        map.put("jcsb006","雨量计"); //
        map.put("jcsb008","管网流量计");
        map.put("jcsb009","水质监测");
        map.put("jcsb010","管网液位计");
//        map.put("jcsb060","水质液位一体机");
        map.put("jcsb081","电子水尺");//水位 水深
        map.put("jcsb082","河道水位计");
//        map.put("jcsb089","泵站液位计");
        map.put("jcsb064","泵站");
    }

    @Value("${special.baseUrl}")
    private String baseUrl;
//    public static final String baseUrl= "http://59.203.83.50:38847";
//    public static final String baseUrl= "http://10.100.120.6:8847";
    public static final String token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjE1OTU1MjEyNTE4IiwidXNlcl9uYW1lIjoic3lzdGVtIiwib3BlbmlkIjoiMSIsInNjb3BlIjpbImFsbCJdLCJuYW1lIjoi5bmz5Y-w566h55CG5ZGYIiwiYXZhdGFyIjpudWxsLCJleHAiOjE2NjYyNjk0OTIsInVzZXJOYW1lIjoic3lzdGVtIiwiYXV0aG9yaXRpZXMiOlsiT1BfMTUxMTE3MjQ5MCIsIk9QXzE5NzYxODI2MzkiLCJPUF83Mzg4MTkyMzkiLCJPUF8xOTAxMzcyNzU0IiwiT1BfMTg5MzEzMzQwNyIsIlJPTEVfQURNSU5JU1RSQVRPUiIsIk9QXzE0ODg1ODI5NDYiXSwianRpIjoiOWY1MGNkOGQtMjVjYi00NTIyLTkzMDgtOTU5MWEyMTQ1NDNkIiwiY2xpZW50X2lkIjoiYTRmNTljM2EtY2RkZS00MzkzLTk2MWMtZWYxYTE2NTUyM2ZmIn0.DZHfoERH8BPqEyBIobnRp1Ku32MSspgGIfgamdVshqE";


    public List<DeviceTypeInfo> getDeviceTypeList(){
        List<DeviceTypeInfo> list = new ArrayList<>();

        for(String key:map.keySet()){
            DeviceTypeInfo info = new DeviceTypeInfo();
            info.setCode(key);
            info.setName(map.get(key));
            getShowList(info);
            list.add(info);
        }
        return list;
    }

    public void getShowList(DeviceTypeInfo info){
        List<DeviceTypeShowVo> list = new ArrayList<>();
        switch (info.getCode()){
            case "jcsb005":
                DeviceTypeShowVo vo = fillVo("water_level","水位","m");
                list.add(vo);
                info.setShowList(list);
                break;
            case "jcsb006":
                DeviceTypeShowVo v1 = fillVo("rainfall","当前降雨量","mm");
                DeviceTypeShowVo v2 = fillVo("rainfall_60min","小时降雨量","mm");
                list.add(v1);
                list.add(v2);
                info.setShowList(list);
                break;
            case "jcsb008":
                DeviceTypeShowVo flow = fillVo("instantaneous_flow","瞬时流量","m³/h");
                list.add(flow);
                info.setShowList(list);
                break;
            case "jcsb009":
                DeviceTypeShowVo vo1 = fillVo("nh3","NH3-N","mg/L");
                DeviceTypeShowVo vo2 = fillVo("cod","COD","mg/L");
                DeviceTypeShowVo vo3 = fillVo("ss","悬浮物","mg/L");
                DeviceTypeShowVo vo4 = fillVo("conductivity","电导率","%");
                list.add(vo1);
                list.add(vo2);
                list.add(vo3);
                list.add(vo4);
                info.setShowList(list);
                break;
            case "jcsb010":
                DeviceTypeShowVo waterVo =  fillVo("water_level","液位","m");
                list.add(waterVo);
                info.setShowList(list);
                break;
            case "jcsb081":
                DeviceTypeShowVo water1 =  fillVo("water_level","水位","m");
                DeviceTypeShowVo water2 =  fillVo("water_dept","水深","m");
                list.add(water1);
                list.add(water2);
                info.setShowList(list);
                break;
            case "jcsb082":
                DeviceTypeShowVo water3 =  fillVo("water_level","水位","m");
                list.add(water3);
                info.setShowList(list);
                break;
            default:
                break;
        }

    }

    private DeviceTypeShowVo fillVo(String code,String name,String unit){
        DeviceTypeShowVo vo = new DeviceTypeShowVo();
        vo.setCode(code);
        vo.setName(name);
        vo.setEnUnit(unit);
        return vo;
    }

    public List<Map<String,Object>> getListByDeviceType(String token,String deviceType){
        List<Map<String,Object>> maps = new ArrayList<>();
        if(deviceType.equals("jcsb064")) {
            maps = getPump(token,maps);
        }else {
            Map<String,Object> headers = new HashMap<>();
            headers.put("Authorization",token);
            MonitorRequest request = new MonitorRequest();
            request.setEquipmentType(deviceType);
            request.setCurrentPage(1L);
            request.setPageSize(1000L);
            String result = forestClient.getListByDeviceType(baseUrl,"cityll-drain-system/v1/monitor/realTimeMonitor/getPageList", headers, request);
            maps = transferRecordDataToListMap(result,maps);

        }
        for(Map<String,Object> map :maps){
            if(map.containsKey("lgtd")){
                BigDecimal lgtd = (BigDecimal) map.get("lgtd");
                BigDecimal lttd = (BigDecimal) map.get("lttd");
                double[] dealDoubles= transferLocation(lgtd.doubleValue(),lttd.doubleValue());
                map.put("lgtd",dealDoubles[0]);
                map.put("lttd",dealDoubles[1]);
            }
        }

        return maps;
    }

    public List<Map<String,Object>>  getPump(String token,List<Map<String,Object>> maps){
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        MonitorRequest request = new MonitorRequest();
        request.setZoneId(null);
        String result = forestClient.getPumpList(baseUrl,"cityll-drain-system/v1/base/pump/gis/queryAllPump", headers, request);
        maps = transferDataToListMap(result,maps);
        return maps;
    }



 /*@Override
    public List<Map<String,Object>> getStationList(String token,String deviceType){
        List<Map<String,Object>> maps = new ArrayList<>();
        if(deviceType.equals("jcsb064")){
            maps = getPump(token,maps);
        }else {
            List<DrainStationTypeRlDeviceType> list = deviceTypeService.getByEquipType(deviceType);
            if(!CollectionUtils.isEmpty(list)){
                List<String> typeList = new ArrayList<>();
                for(DrainStationTypeRlDeviceType rlDeviceType:list){
                    String stationTypeId = rlDeviceType.getStationTypeId();
                    DrainStationChType chType = chTypeService.getById(stationTypeId);
                    if(chType !=null){
                        typeList.add(stationTypeId);
                        break;
                    }
                }
                if(!CollectionUtils.isEmpty(typeList)){
                    Map<String,Object> headers = new HashMap<>();
                    headers.put("Authorization",token);
                    MonitorRequest request = new MonitorRequest();
                    request.setTypeList(typeList);
                    String result = forestClient.getStationList(baseUrl,"cityll-drain-system/v1/base/station/getStationList", headers, request);
                    maps = transferDataToListMap(result,maps);
                }
            }

        }
        List<Map<String,Object>> list = new ArrayList<>();
        for(Map<String,Object> map :maps){
            if("pump".equals(deviceType)){
                list.add(map);
            }else {
                if(map.get("name").equals(map.get(deviceType))){
                    list.add(map);
                }
            }
            if(map.containsKey("lgtd")){
                double[] dealDoubles= transferLocation((Double) map.get("lgtd"),(Double)map.get("lttd"));
                map.put("lgtd",dealDoubles[0]);
                map.put("lttd",dealDoubles[1]);
            }
        }
        return list;

    }*/


    public List<Map<String,Object>> transferDataToListMap(String result,List<Map<String,Object>> maps){
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if(jsonObject.getInteger("code") == 20000){
            JSONArray data = jsonObject.getJSONArray("data");
            if(data !=null){
                String dataStr = data.toJSONString();
                maps = (List<Map<String,Object>>) JSONArray.parse(dataStr);
                System.out.println(JSON.toJSONString(maps));
            }
        }
        return maps;
    }

    public double[] transferLocation(double lng, double lat){
        double[] dealDoubles = CoordinateTransformUtils.wgs84togcj02(lng, lat);
        return  dealDoubles;
    }

    public Map<String,Object> transferDataToMap(String result,Map<String,Object> map){
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if(jsonObject.getInteger("code") == 20000){
            JSONObject data = jsonObject.getJSONObject("data");
            if(data !=null){
                map = JSONObject.parseObject(data.toString(),Map.class);
                System.out.println(JSON.toJSONString(map));
            }
        }
        return map;
    }

    public List<Map<String,Object>> transferRecordDataToListMap(String result,List<Map<String,Object>> maps){
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        if(jsonObject.getInteger("code") == 20000){
            JSONObject data = jsonObject.getJSONObject("data");
            if(data !=null){
                JSONArray record = data.getJSONArray("records");
                if(record !=null){
                    String dataStr = record.toJSONString();
                    maps = (List<Map<String,Object>>) JSONArray.parse(dataStr);
                    System.out.println(JSON.toJSONString(maps));
                }

            }
        }
        return maps;
    }



    public Map<String,Object> getPumpDetail(String token,String id){
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
//        String result = forestClient.selectCifrsDrainMnPumpDtoById("http://59.203.151.138:38847","cityll-drain-system/v1/base/pump/selectCifrsDrainMnPumpDtoById", headers, id);
        String result = forestClient.selectCifrsDrainMnPumpDtoById(baseUrl,"cityll-drain-system/v1/base/pump/selectCifrsDrainMnPumpDtoById", headers, id);
        map = transferDataToMap(result,map);
        return map;
    }







    public List<Map<String,Object>> selectStationAllAlarmList(String token,String stationId){
        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        String result = forestClient.selectStationAllAlarmList(baseUrl,"cityll-drain-system/v1/monitor/alarm/selectStationAllAlarmList", headers, stationId);
        maps = transferDataToListMap(result,maps);
        return maps;
    }


    public Map<String,Object> getStationInfoByStationId(String token,String stationId){
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        String result = forestClient.getStationInfoByStationId(baseUrl,"cityll-drain-system/v1/base/station/getStationInfoByStationId", headers, stationId);
        map = transferDataToMap(result,map);
        return map;
    }

//*
//     * 历史曲线
//     * @param token
//     * @param pointCode
//     * @param sensorCode
//     * @param tagCode
//     * //液位 water_level
//     * //流量 instantaneous_flow 瞬间流量
//     * //水位  water_dept 水深 water_level 水位
//     * //水质 nh3 NH3-N  conductivity 电导率 ss 悬浮物  cod COD
//     * //雨量 rainfall 当前降雨量 rainfall_60min 小时降雨量
//     * @param startTime
//     * @param endTime


    public List<Map<String,Object>>  queryHistoryDataLine(String token,String pointCode,String sensorCode,String tagCode,String startTime,String endTime){
        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        String result = forestClient.queryHistoryDataLine(baseUrl,"cityll-drain-system/v1/bigData/queryHistoryDataLine",
                headers, pointCode,sensorCode,tagCode,startTime,endTime);
        maps = transferDataToListMap(result,maps);
        return maps;
    }

//*
//     * 获取点位信息
//     * @param token
//     * @param coamPointCode
//     * @return


    public List<Map<String,Object>>  getPointByPointCode(String token,String coamPointCode){
        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        String result = forestClient.getPointByPointCode(baseUrl,"cityll-drain-system/v1/base/point/getPointByPointCode", headers, coamPointCode);
        maps = transferRecordDataToListMap(result,maps);
        return maps;

    }
//
//*
//     * 获取关联管线数据
//     * @param token
//     * @param coamSubjectCode
//     * @return


    public List<Map<String,Object>> getPipelineByCoamSubjectCode(String token,String coamSubjectCode){
        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        String result = forestClient.getPipelineByCoamSubjectCode(baseUrl,"cityll-drain-system/v1/base/point/getPipelineByCoamSubjectCode", headers, coamSubjectCode);
        maps = transferRecordDataToListMap(result,maps);
        return maps;
    }

//*
//     * 获取设备信息
//     * @param token
//     * @param coamEquipCode
//     * @return


    public List<Map<String,Object>> getEquipByCoamEquipCode(String token,String coamEquipCode){
        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> headers = new HashMap<>();
        headers.put("Authorization",token);
        String result = forestClient.getEquipByCoamEquipCode(baseUrl,"cityll-drain-system/v1/base/point/getEquipByCoamEquipCode", headers, coamEquipCode);
        maps = transferRecordDataToListMap(result,maps);
        return maps;
    }

}
